package com.example.service;

import com.example.entity.WorkItem;
import com.example.mapper.WorkItemMapper;
import com.example.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WorkItemService {

    private static final Logger logger = LoggerFactory.getLogger(WorkItemService.class);

    @Autowired
    private WorkItemMapper workItemMapper;

    public List<WorkItem> getWorkItemsByProjectId(Integer projectId) {
        if (projectId == null || projectId <= 0) {
            throw new BusinessException.ValidationException("项目ID不能为空且必须大于0");
        }
        
        try {
            List<WorkItem> workItems = workItemMapper.getWorkItemsByProjectId(projectId);
            logger.debug("获取项目{}的工作项成功，共{}个", projectId, workItems.size());
            return workItems;
        } catch (Exception e) {
            logger.error("获取项目工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("获取项目工作项失败", e);
        }
    }

    public List<WorkItem> getAllWorkItems() {
        try {
            List<WorkItem> workItems = workItemMapper.getAllWorkItems();
            logger.debug("获取所有工作项成功，共{}个", workItems.size());
            return workItems;
        } catch (Exception e) {
            logger.error("获取所有工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("获取所有工作项失败", e);
        }
    }

    public WorkItem getWorkItemById(Integer workItemId) {
        if (workItemId == null || workItemId <= 0) {
            throw new BusinessException.ValidationException("工作项ID不能为空且必须大于0");
        }
        
        try {
            WorkItem workItem = workItemMapper.getWorkItemById(workItemId);
            if (workItem == null) {
                throw new BusinessException.DataNotFoundException("工作项不存在");
            }
            return workItem;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("获取工作项详情失败: {}", e.getMessage(), e);
            throw new BusinessException("获取工作项详情失败", e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void createWorkItem(WorkItem workItem) {
        validateWorkItem(workItem);
        
        try {
            workItemMapper.insertWorkItem(workItem);
            logger.info("工作项创建成功: {}", workItem.getTitle());
        } catch (Exception e) {
            logger.error("创建工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("创建工作项失败", e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateWorkItem(WorkItem workItem) {
        validateWorkItem(workItem);
        
        if (workItem.getWorkItemId() == null || workItem.getWorkItemId() <= 0) {
            throw new BusinessException.ValidationException("工作项ID不能为空且必须大于0");
        }
        
        try {
            // 检查工作项是否存在
            WorkItem existingWorkItem = workItemMapper.getWorkItemById(workItem.getWorkItemId());
            if (existingWorkItem == null) {
                throw new BusinessException.DataNotFoundException("要更新的工作项不存在");
            }
            
            workItemMapper.updateWorkItem(workItem);
            logger.info("工作项更新成功: {}", workItem.getTitle());
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("更新工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("更新工作项失败", e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteWorkItem(Integer workItemId) {
        if (workItemId == null || workItemId <= 0) {
            throw new BusinessException.ValidationException("工作项ID不能为空且必须大于0");
        }
        
        try {
            // 检查工作项是否存在
            WorkItem existingWorkItem = workItemMapper.getWorkItemById(workItemId);
            if (existingWorkItem == null) {
                throw new BusinessException.DataNotFoundException("要删除的工作项不存在");
            }
            
            workItemMapper.deleteWorkItem(workItemId);
            logger.info("工作项删除成功: {}", workItemId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("删除工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("删除工作项失败", e);
        }
    }

    public List<WorkItem> getWorkItemsByStatus(String status) {
        if (status == null || status.trim().isEmpty()) {
            throw new BusinessException.ValidationException("状态不能为空");
        }
        
        try {
            List<WorkItem> workItems = workItemMapper.getWorkItemsByStatus(status);
            logger.debug("根据状态{}获取工作项成功，共{}个", status, workItems.size());
            return workItems;
        } catch (Exception e) {
            logger.error("根据状态获取工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("根据状态获取工作项失败", e);
        }
    }

    public List<WorkItem> getWorkItemsByResponsiblePerson(String responsiblePerson) {
        if (responsiblePerson == null || responsiblePerson.trim().isEmpty()) {
            throw new BusinessException.ValidationException("负责人不能为空");
        }
        
        try {
            List<WorkItem> workItems = workItemMapper.getWorkItemsByResponsiblePerson(responsiblePerson);
            logger.debug("根据负责人{}获取工作项成功，共{}个", responsiblePerson, workItems.size());
            return workItems;
        } catch (Exception e) {
            logger.error("根据负责人获取工作项失败: {}", e.getMessage(), e);
            throw new BusinessException("根据负责人获取工作项失败", e);
        }
    }

    // 新增：负责人任务统计方法 - 可以按项目ID筛选
    public int countWorkItemsByResponsiblePerson(String responsiblePerson, Integer projectId) {
        if (responsiblePerson == null || responsiblePerson.trim().isEmpty()) {
            throw new BusinessException.ValidationException("负责人不能为空");
        }
        
        try {
            return workItemMapper.countWorkItemsByResponsiblePerson(responsiblePerson, projectId);
        } catch (Exception e) {
            logger.error("统计负责人任务数量失败: {}", e.getMessage(), e);
            throw new BusinessException("统计负责人任务数量失败", e);
        }
    }
    
    private void validateWorkItem(WorkItem workItem) {
        if (workItem == null) {
            throw new BusinessException.ValidationException("工作项信息不能为空");
        }
        if (workItem.getTitle() == null || workItem.getTitle().trim().isEmpty()) {
            throw new BusinessException.ValidationException("工作项标题不能为空");
        }
        if (workItem.getProjectId() == null || workItem.getProjectId() <= 0) {
            throw new BusinessException.ValidationException("项目ID不能为空且必须大于0");
        }
        if (workItem.getTitle().length() > 100) {
            throw new BusinessException.ValidationException("工作项标题长度不能超过100个字符");
        }
    }

    
    
}